<?php


namespace Frieza\Modules\Position\Actions;

use Doraemon\model\AdmOperateLog;
use Doraemon\model\Phone;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\tools\Checker;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class ChangePhone extends RowAction
{

    public $name = '修改用户手机号';

    public function handle($uid,Request $request)
    {
        $new_phone = $request->get("new_phone");
        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;
        if (empty($new_phone)) {
            return $this->response()->error('请输入手机号');
        }
        if (!is_numeric($new_phone)) {
            return $this->response()->error('手机号输入有误');
        }
        if (!preg_match("/^[0-9]+$/", $new_phone)) {
            return $this->response()->error('手机号格式错误');
        }
        //新手机号加密
        $encrypt_new_phone = PhoneCrypto::encrypt($new_phone, PhoneCrypto::CLIENT_DORAEMON, PhoneCrypto::VERSIN);
        //查询新手机号是否存在
        $new_res = Phone::getInfoByPhone($encrypt_new_phone);
        if (!empty($new_res)) {
            return $this->response()->error('该手机号已经存在，不需要更换');
        }
        //获取旧的手机号
//        $encrypt_old_phone = Phone::getUserPhone($uid);
        $photoInfo = Phone::getByUid($uid);
        $encrypt_old_phone = $photoInfo['phone'];

        $data = [
            'encrypt_phone' => $encrypt_new_phone,
            'hidden_phone' => PhoneCrypto::mask($new_phone),
        ];
        $res = Phone::updateInfo($uid, $encrypt_old_phone, $data);
        if (empty($res)) {
            return $this->response()->error('手机号修改失败,请稍后重试!');
        }
        AdmOperateLog::addLog($uid,AdmOperateLog::$operate_type['edit_phone'],$admin_id,$admin_name,$encrypt_old_phone,$encrypt_new_phone);
        return $this->response()->success('用户手机号修改成功!')->refresh();

    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function form($request)
    {
        $this->text('new_phone', '新手机号')->required()->help('输入手机号');

    }
}